package vn.ebuzz.sms.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import vn.ebuzz.sms.core.AESGenerator;
import vn.ebuzz.sms.core.Configuration;
import vn.ebuzz.sms.core.Incoming;
import vn.ebuzz.sms.core.Util;
import vn.ebuzz.sms.worker.IncomingQueue;

public class EndpointServlet extends HttpServlet {	
	private static Logger log = Logger.getLogger("endpoint");
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String cpId = request.getParameter("cpId");
		String data = request.getParameter("data");
		String uniqueId = request.getParameter("uniqueId");
		
		PrintWriter out = response.getWriter();
		if(!Util.isValidParam(cpId) || !Util.isValidParam(data) || !Util.isValidParam(uniqueId)){
			String result = "Missing param";
			out.print(result);
			log.info("Endpoint: " + result);
			return;
		}
		data=data.replace(" ", "+");
		
		String decrypted = AESGenerator.decrypt(data, Configuration.CPKEY);
		if(!Util.isValidParam(decrypted)){
			String result = "Cannot decrypt " + data;
			out.print(result);
			log.info("Endpoint: " + result);
			return;			
		}
		
		String[] fields = decrypted.split("\\|");
		HashMap<String, String> params = new HashMap<String, String>();
		for(String field : fields){
			if(field.split("=", 2).length == 2){
				String key = field.split("=", 2)[0];
				String value = field.split("=", 2)[1];
				params.put(key, value);
			}
		}

		Incoming in = new Incoming();
		in.setSender(params.get("msisdn"));
		in.setReceiver(params.get("sn"));
		in.setMessage(params.get("msg"));
		in.setMo_id(params.get("moId"));
		in.setSession_id(params.get("sId"));
		in.setUnique_id(uniqueId);
		
		boolean isPush = false;
		for(String s : Configuration.MDOORKEY){
			if(in.getMessage().toUpperCase().startsWith(s))
				isPush = true;
		}
		if(isPush){
			in.setStatus(Configuration.MO_QUEUED2PUSH);
		}
		else{
			in.setStatus(Configuration.MO_QUEUED);
		}
		String result = in.getSession_id() + "|" + in.getMo_id() + "|" + in.getSender() + "|" + in.getReceiver() + "|" + in.getMessage();
		out.print(result);
		log.info(result);
	
		log.info("Endpoint: " + "Add to IncomingQueue");
		IncomingQueue queue = IncomingQueue.getInstance();
		queue.add2Queue(in);
		log.info("Endpoint: " + "MO received");
		return;
	}
}
